<?php

namespace App\Http\Controllers;

use App\Models\CompanyCertificationDetail;
use App\Utils\CommonUtil;
use App\Utils\OptionUtil;
use App\Utils\RegionUtil;
use Illuminate\Http\Request;

class CompanyCertificationDetailController extends BaseController
{
    public function index(Request $request)
    {
        $list     = [];
        $paginate = CompanyCertificationDetail::with('companyCertification')->paginate(10);

        /** @var CompanyCertificationDetail $detail */
        foreach ($paginate->items() as $detail) {
            $val = [];
            foreach ($detail->toArray() as $key => $value) {
                $val[CommonUtil::underscoreToCamelCase($key)] = $value;
            }

            $val['companyCertification']['agreementOriginName'] = OptionUtil::getOptionNameByKey(OptionUtil::OPTION_NAME_AGREEMENT_ORIGIN, $val['companyCertification']['agreement_origin']);
            $val['companyCertificationTypeName']                = OptionUtil::getOptionNameByKey(OptionUtil::OPTION_NAME_AUDIT_TYPE, $val['companyCertificationType']);

            $list[] = $val;
        }

        return self::responseJson([
            'list'  => $list,
            'pages' => $paginate->lastPage(),
            'total' => $paginate->total(),
        ]);
    }

    public function edit(Request $request)
    {
        $id    = $request->route('id');
        $posts = $request->post();

        $data = [];
        foreach ($posts as $key => $value) {
            $data[CommonUtil::camelCaseToUnderscore($key)] = $value;
        }

        $data['modify_time'] = date('Y-m-d H:i:s');

        CompanyCertificationDetail::query()->where('id', $id)->update($data);

        return self::responseMsg();
    }

    public function show(Request $request)
    {
        $id   = $request->route('id');
        $item = CompanyCertificationDetail::query()->where('id', $id)->first();

        $detail = [];
        foreach ($item->attributesToArray() as $key => $value) {
            $detail[CommonUtil::underscoreToCamelCase($key)] = $value;
        }

        return self::responseJson($detail);
    }
}
